import axios from 'axios';
import { Loading, Message } from 'element-ui';
import qs from 'qs';

/**
 * 统一的错误提示
 * */
const errorTip = (message, code = null) => {
  let msg = message.length > 30 ? '运行报错' : message;
  console.error('错误====>===>', message, code);
  Message.error(msg);
};


const baseURL = process.env.NODE_ENV === 'production' ? 'http://127.0.0.1:8888/' : 'http://127.0.0.1:8888/';
const $axios = axios.create({
  baseURL,
  headers: {
    // 跨域请求 这个配置不能少
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
  },
  timeout: 1000 * 10,
  paramsSerializer: function (params) { // 请求数组需要
    return qs.stringify(params, { arrayFormat: 'brackets' });
  }
});

$axios.interceptors.request.use(axiosConfig => {
  return axiosConfig;
},
  error => {
    errorTip(error.response);
  }
);

axios.interceptors.response.use(response => {
  return response;
}, (error) => {
  errorTip(error.response);
  return Promise.reject(error)
});

export default {
  // get请求
  get(url, param) {
    let loadingInstance = Loading.service({ fullscreen: true });
    return new Promise((resolve, reject) => {
      $axios({
        method: 'get',
        url,
        params: param,
      }).then(res => { 
        resolve(res); 
        loadingInstance.close();
      }).catch(error => {
        reject(error.response)
        loadingInstance.close();
      });

    });
  },
  // post请求 
  post(url, param) {
    let loadingInstance = Loading.service({ fullscreen: true });
    return new Promise((resolve, reject) => {
      $axios({
        method: 'post',
        url,
        data: param,
        headers: {
          'Content-Type': 'application/json'
        },
      }).then(res => {
        resolve(res);
        loadingInstance.close();
      }).catch(error => {
        reject(error.response)
        loadingInstance.close();
      });
    });
  },
  // 文件上传请求
  filePost(url, param) {
    let loadingInstance = Loading.service({ fullscreen: true });
    return new Promise((resolve, reject) => {
      $axios({
        method: 'post',
        url,
        data: param,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      }).then(res => {
        resolve(res);
        loadingInstance.close();
      }).catch(error => {
        reject(error.response)
        loadingInstance.close();
      });
    });
  },
}